﻿using System;
using System.Configuration;
using System.Web.Mvc;
using WikeSoft.Core.Extension;
using WikeSoft.Enterprise.Interfaces.Sys;


namespace WikeSoft.Web
{
    /// <summary>
    /// 权限过滤器
    /// </summary>
    public class RightAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!NeedValidateRights(filterContext))
                return;
            var url = filterContext.HttpContext.Request.Url;
            if (url == null)
                return;

            var visitUrl = url.AbsolutePath;
            var principal = filterContext.HttpContext.User;
           
            if (visitUrl.IsBlank()) return;
            var pageServic = DependencyResolver.Current.GetService<IPageService>();
            var data = pageServic.FindByPagePath(visitUrl);
            if (data != null)
            {
                var service = DependencyResolver.Current.GetService<IPageService>();

                if (service.HasRight(principal.Identity.GetLoginUserId(), visitUrl)) return;

                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    var tips = "你没有访问权限";
                    filterContext.Result = new JsonResult
                    {
                        Data = new { success = false, message = tips },
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                }
                else
                {
                    filterContext.Result = new ViewResult
                    {
                        ViewName = "~/Views/Shared/NoRight.cshtml"
                    };
                }
            }
           
        }

        /// <summary>
        /// 是否需要验证权限
        /// </summary>
        /// <param name="filterContext"></param>
        /// <returns></returns>
        private static bool NeedValidateRights(ActionExecutingContext filterContext)
        {
            var rightEnabled = Convert.ToBoolean(ConfigurationManager.AppSettings["rightEnabled"]);
            var anonymousType = typeof(AllowAnonymousAttribute);
            var actionDescriptor = filterContext.ActionDescriptor;
            var controllerDescripter = filterContext.ActionDescriptor.ControllerDescriptor;
            var ignoreRight = actionDescriptor.IsDefined(anonymousType, false) ||
                              controllerDescripter.IsDefined(anonymousType, false);
            var isChild = filterContext.IsChildAction;
            return rightEnabled && !ignoreRight && !isChild;
        }
    }
}